package com.fitness.front.aop.dw;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.fitness.front.aop.LogMessage;
import com.fitness.front.modal.course.dto.CourseReserveDto;
import com.fitness.front.modal.course.entity.Course;
import com.fitness.front.modal.datavisual.MemberBehavior;
import com.fitness.front.service.ICourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Date;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class CourseReserveAspect {

    private final ICourseService courseService;

    @Pointcut("execution(* com.fitness.front.controller.CourseReserveController.reserveCourse(..))")
    public void courseReserveLogPointcut(){}

    @Around("courseReserveLogPointcut()")
    public Object coursePVLog(ProceedingJoinPoint point) throws Throwable{
        try {
            Object result = point.proceed();
            CourseReserveDto reserveDto = (CourseReserveDto)point.getArgs()[0];
            MemberBehavior memberBehavior = new MemberBehavior();
            memberBehavior.setCourseId(reserveDto.getCourseId());
            Course course = courseService.getById(reserveDto.getCourseId());
            memberBehavior.setCategoryId(course.getCategoryId());
            memberBehavior.setBehaviorType(MemberBehavior.RESERVE);
            memberBehavior.setMemberId(reserveDto.getMemberId());
            memberBehavior.setTimestamp(System.currentTimeMillis());
            LogMessage<MemberBehavior> logMessage = new LogMessage<>(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"),
                    LogMessage.COURSE_RESERVE_TYPE,memberBehavior);
            log.info("{}", JSONUtil.toJsonStr(logMessage));
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return null;
    }
}
